<template>
  <view class="page">
    <view class="tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index" 
        :class="['tab-item', activeTab === tab.value ? 'active' : '']"
        @click="switchTab(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <view class="content">
      <view v-if="loading" class="loading">加载中...</view>
      <view v-else-if="list.length === 0" class="empty">
        <image src="/static/img/empty.png" class="empty-img" mode="aspectFit"></image>
        <text class="empty-text">暂无借阅记录</text>
      </view>
      <view v-else class="list">
        <view v-for="item in list" :key="item.id" class="item">
          <image :src="item.cover || '/static/img/default-item.png'" class="cover" mode="aspectFill"></image>
          <view class="info">
            <text class="title">{{ item.book_name }}</text>
            <text class="author">{{ item.author }}</text>
            <text class="date">借阅日期：{{ formatDate(item.borrow_date) }}</text>
            <text class="date">到期日期：{{ formatDate(item.due_date) }}</text>
            <text v-if="item.return_date" class="date">归还日期：{{ formatDate(item.return_date) }}</text>
          </view>
          <view class="actions">
            <view :class="['status', getStatusClass(item.status)]">
              {{ getStatusText(item.status) }}
            </view>
            <!-- 修改：续借申请功能 -->
            <button v-if="item.status === 'borrowed' && canRenew(item)" class="action-btn" @click="handleRenewApplication(item)">
              申请续借
            </button>
            <button v-if="item.status === 'borrowed' && !canRenew(item)" class="action-btn disabled" disabled>
              {{ getRenewDisabledText(item) }}
            </button>
            <button v-if="item.status === 'borrowed'" class="action-btn primary" @click="returnBook(item)">
              归还
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <view class="stats">
      <view class="stat-item">
        <text class="stat-value">{{ stats.borrowed_count || 0 }}</text>
        <text class="stat-label">借阅中</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ stats.returned_count || 0 }}</text>
        <text class="stat-label">已归还</text>
      </view>
      <view class="stat-item">
        <text class="stat-value">{{ stats.overdue_count || 0 }}</text>
        <text class="stat-label">已逾期</text>
      </view>
    </view>
  </view>
</template>

<script>
import { myRequest } from '@/util/request.js';

export default {
  name: 'Borrow',
  data() {
    return {
      activeTab: '',
      tabs: [
        { label: '全部', value: '' },
        { label: '借阅中', value: 'borrowed' },
        { label: '已归还', value: 'returned' },
        { label: '已逾期', value: 'overdue' }
      ],
      list: [],
      loading: false,
      stats: {}
    };
  },
  onShow() {
    this.fetchList();
    this.fetchStats();
  },
  methods: {
    async fetchList() {
      this.loading = true;
      try {
        const params = this.activeTab ? { status: this.activeTab } : {};
        const data = await myRequest({ 
          url: '/api/borrow/records', 
          method: 'GET',
          data: params
        });
        this.list = data;
      } catch (e) {
        console.error('获取借阅记录失败', e);
      } finally {
        this.loading = false;
      }
    },
    async fetchStats() {
      try {
        const data = await myRequest({ url: '/api/borrow/stats', method: 'GET' });
        this.stats = data;
      } catch (e) {
        console.error('获取统计失败', e);
      }
    },
    switchTab(value) {
      this.activeTab = value;
      this.fetchList();
    },
    getStatusText(status) {
      const map = {
        'borrowed': '借阅中',
        'returned': '已归还',
        'overdue': '已逾期'
      };
      return map[status] || status;
    },
    getStatusClass(status) {
      const map = {
        'borrowed': 'success',
        'returned': 'info',
        'overdue': 'danger'
      };
      return map[status] || '';
    },
    formatDate(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    },
    // 修改：续借申请功能
    async handleRenewApplication(item) {
      uni.showModal({
        title: '续借申请',
        content: `确定要申请续借《${item.book_name}》吗？需要等待管理员审核。`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await myRequest({
                url: '/api/renew-applications/apply',
                method: 'POST',
                data: { borrowRecordId: item.id }
              });
              uni.showToast({ title: '续借申请已提交，请等待审批', icon: 'success' });
              // 刷新列表
              setTimeout(() => {
                this.fetchList();
              }, 1000);
            } catch (e) {
              console.error('续借申请失败', e);
              uni.showToast({ title: e.message || '续借申请失败', icon: 'none' });
            }
          }
        }
      });
    },

    // 新增：检查是否可以续借
    canRenew(item) {
      const maxRenewTimes = 2; // 最大续借次数，可从系统设置获取
      return item.renew_count < maxRenewTimes;
    },

    // 新增：获取续借禁用原因
    getRenewDisabledText(item) {
      const maxRenewTimes = 2;
      if (item.renew_count >= maxRenewTimes) {
        return '续借次数已用完';
      }
      return '不可续借';
    },
    async returnBook(item) {
      uni.showModal({
        title: '归还图书',
        content: `确定要归还《${item.book_name}》吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await myRequest({ 
                url: '/api/borrow/return', 
                method: 'POST', 
                data: { borrowId: item.id, condition: 'good' } 
              });
              uni.showToast({ title: '归还成功', icon: 'success' });
              this.fetchList();
              this.fetchStats();
            } catch (e) {
              console.error('归还失败', e);
            }
          }
        }
      });
    }
  }
}
</script>

<style scoped>
.page { 
  display: flex; 
  flex-direction: column; 
  min-height: 100vh; 
  background: #f5f5f5; 
}

.tabs { 
  display: flex; 
  background: #fff; 
  border-bottom: 1rpx solid #eee; 
}

.tab-item { 
  flex: 1; 
  text-align: center; 
  padding: 28rpx 0; 
  font-size: 28rpx; 
  color: #666; 
  position: relative; 
}

.tab-item.active { 
  color: #3E88F0; 
  font-weight: 700; 
}

.tab-item.active::after { 
  content: ''; 
  position: absolute; 
  bottom: 0; 
  left: 50%; 
  transform: translateX(-50%); 
  width: 60rpx; 
  height: 4rpx; 
  background: #3E88F0; 
  border-radius: 2rpx; 
}

.content { 
  flex: 1; 
  padding: 20rpx; 
}

.loading, .empty { 
  text-align: center; 
  color: #999; 
  padding: 100rpx 0; 
}

.empty-img { 
  width: 200rpx; 
  height: 200rpx; 
  margin-bottom: 20rpx; 
}

.empty-text { 
  font-size: 28rpx; 
  color: #999; 
}

.list { 
  display: flex; 
  flex-direction: column; 
  gap: 20rpx; 
}

.item { 
  display: flex; 
  gap: 20rpx; 
  background: #fff; 
  border-radius: 12rpx; 
  padding: 20rpx; 
}

.cover { 
  width: 140rpx; 
  height: 180rpx; 
  border-radius: 8rpx; 
  background: #f5f5f5; 
}

.info { 
  flex: 1; 
  display: flex; 
  flex-direction: column; 
  gap: 8rpx; 
}

.title { 
  font-size: 30rpx; 
  color: #333; 
  font-weight: 700; 
  overflow: hidden; 
  text-overflow: ellipsis; 
  white-space: nowrap; 
}

.author { 
  font-size: 24rpx; 
  color: #888; 
}

.date { 
  font-size: 24rpx; 
  color: #999; 
}

.actions { 
  display: flex; 
  flex-direction: column; 
  justify-content: center; 
  gap: 12rpx; 
  align-items: flex-end; 
}

.status { 
  padding: 8rpx 20rpx; 
  font-size: 24rpx; 
  border-radius: 20rpx; 
  white-space: nowrap; 
}

.status.success { 
  background: #e6f7ff; 
  color: #1890ff; 
}

.status.info { 
  background: #f0f0f0; 
  color: #666; 
}

.status.danger { 
  background: #fff1f0; 
  color: #ff4d4f; 
}

.action-btn { 
  padding: 8rpx 24rpx; 
  font-size: 24rpx; 
  border-radius: 20rpx; 
  background: #fff; 
  color: #3E88F0; 
  border: 2rpx solid #3E88F0; 
}

.action-btn.primary { 
  background: #3E88F0; 
  color: #fff; 
  border-color: #3E88F0; 
}

.stats { 
  display: flex; 
  background: #fff; 
  border-top: 1rpx solid #eee; 
  padding: 20rpx 0; 
}

.stat-item { 
  flex: 1; 
  display: flex; 
  flex-direction: column; 
  align-items: center; 
  gap: 8rpx; 
}

.stat-value { 
  font-size: 36rpx; 
  color: #3E88F0; 
  font-weight: 700; 
}

.stat-label { 
  font-size: 24rpx; 
  color: #999; 
}
</style>

